import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Login from '@/views/Login.vue'
import { useAuthStore } from '@/stores/index.js'
const router = createRouter({
  // 创建路由
  history: createWebHistory(import.meta.env.VITE_API_BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      redirect: '/line',
      children: [
        {
          path: 'line',
          name: 'line',
          component: () => import('../views/line-view/index.vue'),
        },
        {
          path: 'water',
          name: 'water',
          component: () => import('../views/water-view/index.vue'),
        },
        {
          path: 'pie',
          name: 'pie',
          component: () => import('../views/pie-view/index.vue'),
        },
        {
          path: 'bar',
          name: 'bar',
          component: () => import('../views/bar-view/index.vue'),
        },
        // 词云
        {
          path: 'wordCloud',
          name: 'wordCloud',
          component: () => import('../views/wordCloud-view/index.vue'),
        },
        // 雷达图
        {
          path: 'radar',
          name: 'radar',
          component: () => import('../views/radar-view/index.vue'),
        },
        // 仪表盘
        {
          path: 'gauge',
          name: 'gauge',
          component: () => import('../views/gauge-view/index.vue'),
        },
        // Vue组件
        {
          path: 'vue-component',
          name: 'vue-component',
          component: () => import('../views/vue-component/index.vue'),
        },
      ],
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
    },
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 白名单
  const whitelist = ['/login']

  // 检查目标路由是否在白名单中
  if (whitelist.includes(to.path)) {
    return next()
  }

  // 获取 token
  const token = useAuthStore().token
  // console.log(token)

  if (token) {
    // 如果有 token，允许进入目标路由
    next()
  } else {
    // 如果没有 token，重定向到登录页面
    next('/login')
  }
})

export default router
